package cn.com.header.zbpk.account.service.impl;

import cn.com.header.core.IPage;
import cn.com.header.core.ISort;
import cn.com.header.core.vo.TreeVO;
import cn.com.header.zbpk.account.entity.Authority;
import cn.com.header.zbpk.account.mapper.IAuthorityMapper;
import cn.com.header.zbpk.account.service.IAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Yuanyifeng
 * @date 2017-11-18
 * @time 14:00
 */
@Service
public class AuthorityServiceImpl implements IAuthorityService {
    @Autowired
    IAuthorityMapper authMapper;
    @Override
    public List<TreeVO> getAuthByUserIdAndParentId(Long userId) {
        //获取一级菜单
        List<Authority> topAuthList=authMapper.getAuthByUserIdAndParentId(userId,null);
        List<TreeVO> authTreeList=new ArrayList<TreeVO>();
        TreeVO authVO;
        for(Authority auth:topAuthList){
            authVO=new TreeVO();
            authVO.setId(auth.getId());
            authVO.setLevel(auth.getLevel());
            authVO.setName(auth.getName());
            authVO.setParentId(null);
            diguiAuth(userId,auth,authVO);//递归
            authTreeList.add(authVO);
        }
        return authTreeList;
    }

    @Override
    public List<Authority> getAllAuth() {
        return authMapper.getAllAuth();
    }

    @Override
    public Set<Authority> queryAuthorityListByTemplate(Authority authority, Set<String> fields, Set<ISort> sortSet, IPage page) {
        return authMapper.loads(authority, fields, sortSet, page);
    }
    @Override
    public Set<String> queryAuthorityByUserId(Long id) {
        return authMapper.loadByUserId(id, null);
    }
    /**
     * 递归获取孩子节点
     * @param userId
     * @param auth
     * @param treeVO
     */
    void diguiAuth(Long userId,Authority auth,TreeVO treeVO){
        List<Authority> authList=authMapper.getAuthByUserIdAndParentId(userId,auth.getId());
        if(!authList.isEmpty()){//如果有孩子节点才递归
            List<TreeVO> chileTreeList=new ArrayList<TreeVO>();
            TreeVO authVO;
            for(Authority childAuth:authList){
                authVO=new TreeVO();
                authVO.setId(childAuth.getId());
                authVO.setLevel(childAuth.getLevel());
                authVO.setName(childAuth.getName());
                authVO.setParentId(auth.getId());
                diguiAuth(userId,childAuth,authVO);
                chileTreeList.add(authVO);
            }
            treeVO.setChildren(chileTreeList);
        }
    }

}
